frontend/pages/api/nauth/[...nextauth].js (view raw)
1import NextAuth from 'next-auth';
2import CredentialsProvider from 'next-auth/providers/credentials';
3import GoogleProvider from 'next-auth/providers/google';
4
5const STRAPI_URL = 'http://localhost:1337';
6
7const authHandler = NextAuth({
8 providers: [
9 CredentialsProvider({
10 name: 'Strapi',
11 credentials: {
12 email: {label: 'Email', type: 'text'},
13 password: {label: 'Password', type: 'password'},
14 },
15 async authorize(credentials, req) {
16 const response = await fetch(`${STRAPI_URL}/api/auth/local`, {
17 method: 'POST',
18 headers: {'Content-Type': 'application/json'},
19 body: JSON.stringify({
20 identifier: credentials.email,
21 password: credentials.password,
22 }),
23 });
24 const data = await response.json();
25 if (data?.error?.message === 'Your account email is not confirmed')
26 throw new Error('EmailNotConfirmed');
27 else if (!data?.jwt) return null;
28 else {
29 const {user, jwt} = data;
30 return {...user, jwt};
31 }
32 },
33 }),
34 GoogleProvider({
35 clientId: process.env.GOOGLE_CLIENT_ID,
36 clientSecret: process.env.GOOGLE_CLIENT_SECRET,
37 }),
38 ],
39 session: {
40 jwt: true,
41 },
42 callbacks: {
43 jwt: async params => {
44 const {token, user, account} = params;
45
46 // Google Auth
47 if (account?.provider === 'google') {
48 const strapiUrl = 'http://localhost:1337';
49 const response = await fetch(
50 `${STRAPI_URL}/api/auth/${account.provider}/callback?access_token=${account?.access_token}`
51 );
52 const data = await response.json();
53 token.id = data.user.id;
54 token.jwt = data.jwt;
55 token.email = data.user.email;
56 token.username = data.user.firstname;
57 token.lang = data.user.lang?.toLowerCase();
58 token.provider = account.provider;
59 token.userCreatedAt = data.user.createdAt;
60 }
61
62 // Strapi Auth
63 else if (user) {
64 token.id = user.id;
65 token.jwt = user.jwt;
66 token.email = user.email;
67 token.username = user.firstname;
68 token.lang = user.lang?.toLowerCase();
69 token.provider = account.provider;
70 token.userCreatedAt = user.createdAt;
71 }
72
73 return token;
74 },
75 session: async params => {
76 const {session, token} = params;
77 if (session) {
78 session.token = token;
79 session.user.name = token.username;
80 session.user.lang = token.lang;
81 }
82 return session;
83 },
84 },
85 pages: {
86 signIn: '/auth/login',
87 error: '/auth/login',
88 },
89});
90
91export default async function handler(...params) {
92 await authHandler(...params);
93}